#include <stdlib.h>
#include <stdio.h>
#include <avr/io.h>
#include <avr/iom32.h>
//#include <avr/iotn45.h>
#include <util/delay.h>
#include <util/atomic.h>
#include <inttypes.h>

#include "SoftUart.h"

#define SOFT_UART_BAUD 26

// 22 = 38400

#define SET_TX_HIGH() SOFT_UART_TX_PORT |= _BV(SOFT_UART_TX)
#define SET_TX_LOW() SOFT_UART_TX_PORT &= ~_BV(SOFT_UART_TX)


void SoftUartInit()
{
	SOFT_UART_TX_DDR |= _BV(SOFT_UART_TX);	//TX = OUTPUT
	SOFT_UART_TX_PORT |= _BV(SOFT_UART_TX);
}

void SoftUart_putc(uint8_t tByte)
{
	ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
	{
		unsigned int i;

		SET_TX_LOW();
		_delay_us(SOFT_UART_BAUD);
		//__asm__ __volatile__("nop");
		for(i=0;i<8;i++)
		{

			if((tByte & (1<<i)))
			{
				SET_TX_HIGH();
				_delay_us(SOFT_UART_BAUD-3);
			} else {
				SET_TX_LOW();
				_delay_us(SOFT_UART_BAUD);
			}
		}
		SET_TX_HIGH();
		_delay_us(SOFT_UART_BAUD);
	}
}

void SoftUart_puts(char* tString)
{
	while(*tString)
	{
		SoftUart_putc(*tString++);
	}
}

// EOF SoftUart.c $ID 00001.b BrentBXR - Brent C. Reamer (2011-2012) - GNU  //
